In this example, we will teach you how to bind a TreeView using a DataTable in Vb.NET. First, create a WinForm Project in Visual Studio, Select Vb.NET as the language. Then, add a TreeView control to the main form.
DataBase
And the Code:
VB.NET
Sub BindTreeView() Dim connetionString = "Data Source=TutorialsPanel-DB\SQLEXPRESS; Initial Catalog=TutorialsPanel;Integrated Security=True;" Dim conn As System.Data.SqlClient.SqlConnection = New SqlClient.SqlConnection(connetionString) Dim da As New SqlDataAdapter Dim cmd As New SqlCommand Dim dt As New DataTable Dim pke(0) As DataColumn Dim i As Integer Dim j As Integer Try cmd.CommandText = "Select ID, LanguageName from ProgrammingLanguage Order by LanguageName ASC" da.SelectCommand = cmd da.SelectCommand.Connection = conn da.Fill(dt) pke(0) = dt.Columns("ID") dt.PrimaryKey = pke conn.Close() myTreeView.Nodes.Add("LanguageName") For j = 0 To dt.Rows.Count - 1 myTreeView.Nodes(i).Nodes.Add(dt.Rows(j).Item("LanguageName")) Next Catch ex As Exception MsgBox(ex.Message) End Try End Sub
Now run the solution:
Now we need to show what the user selects in a label. First, let’s add a label to our form. Then add the code below to the AfterSelect Event:
Private Sub myTreeView_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles myTreeView.AfterSelect lblSelected.Text = myTreeView.SelectedNode.FullPath End Sub
Then run the solution:
Comments